﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace OpenWaves.ActivityFeed.Web.Tests
{
    public partial class UpdatesGeneratorDetails : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                lstUsers.DataSource =
                    FakeUserProfileProvider.Users.Select(u => new {Id = u.Key, DisplayName = u.Value.Name}).ToList();
                lstUsers.DataBind();
            }
        }

        protected void btnGenerateUpdates_OnClick(object sender, EventArgs e)
        {
            var updatesGenerator = new UpdatesGenerator(HttpContext.Current.Server.MapPath("~\\loremIpsum.txt"));
            var options = new UpdatesGeneratorOptions();

            options.NumberOfUpdates = int.Parse(this.txtNumberOfUpdates.Text);
            this.SetRange(options.NumberOfSentencesForUpdate, txtNumberOfSentencesForUpdateMin, txtNumberOfSentencesForUpdateMax);
            this.SetRange(options.NumberOfCommentsForUpdate, txtNumberOfCommentsForUpdateMin, txtNumberOfCommentsForUpdateMax);
            this.SetRange(options.NumberOfSentencesForComment, txtNumberOfSentencesForCommentMin, txtNumberOfSentencesForCommentMax);
            this.SetRange(options.MinutesDalayBetweenUpdates, txtMinutesDalayBetweenUpdatesMin, txtMinutesDalayBetweenUpdatesMax);

            var users = 
                (
                    from item in this.lstUsers.Items 
                    select ((CheckBox) item.FindControl("chkUser")) into checkBox 
                    where checkBox.Checked select checkBox.Attributes["Value"]
                ).ToList();

            if (users.Count == 0)
            {
                users.Add("john");
            }

            options.Users.Clear();
            options.Users.AddRange(users);
            options.Topics.Clear();
            if (!string.IsNullOrWhiteSpace(this.txtTopics.Text))
            {
                options.Topics.AddRange(this.txtTopics.Text.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).Select(t => new Topic(t)));
            }
            updatesGenerator.GenerateUpdates(options);
        }

        private void SetRange(DataRange<int> range, TextBox txtMin, TextBox txtMax)
        {
            range.MinValue = this.GetValue(txtMin);
            range.MaxValue = this.GetValue(txtMax);
        }

        private int GetValue(TextBox txt)
        {
            int result;
            if ( int.TryParse(txt.Text, out result))
            {
                return result;
            }
            return 0;
        }
    }
}